package top.kaoshanji.p1ch08a;

/**
 * 代码清单-p1ch08a-166页a：初始化引用的4种方式
 * author kaoshanji
 * ^_^
 * create time 2025/3/9 15:09
 */
public class Bath {

    // 在定义时初始化
    private String s1 = "Happy1", s2 = "Happy2", s3, s4;
    private Soap castile;
    private int i;
    private float toy;

    // 在构造器里初始化
    public Bath() {
        System.out.println("Inside Bath()");
        s3 = "Joy3";
        toy = 3.14f;
        castile = new Soap();
    }

    // 在代码块里初始化
    {
        i = 47;
    }

    @Override
    public String toString() {
        // 延迟初始化
        if (s4 == null) {
            s4 = "Joy4";
        }

        return "Bath{" +
                "s1='" + s1 + '\'' +
                ", s2='" + s2 + '\'' +
                ", s3='" + s3 + '\'' +
                ", s4='" + s4 + '\'' +
                ", castile=" + castile +
                ", i=" + i +
                ", toy=" + toy +
                '}';
    }

    public static void main(String[] args) {
        Bath b = new Bath();
        System.out.println(b);
    }

}

class Soap {
    private String s;

    Soap() {
        System.out.println("Soap()");
        s = "Constructed";
    }

    @Override
    public String toString() {
        return s;
    }
}


